package com.industrial.premu.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.file.FileNameUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.industrial.common.core.utils.DateUtils;
import com.industrial.common.core.utils.StringUtils;
import com.industrial.common.security.utils.SecurityUtils;
import com.industrial.premu.domain.PreMuCompanyInfo;
import com.industrial.premu.domain.PreMuCompanyTax;
import com.industrial.premu.domain.sqsj.PreMuImportLog;
import com.industrial.premu.domain.sqsj.PreMuImportShuiwu;
import com.industrial.premu.mapper.PreMuCompanyInfoMapper;
import com.industrial.premu.mapper.PreMuCompanyTaxMapper;
import com.industrial.premu.mapper.sqsj.PreMuImportLogMapper;
import com.industrial.premu.mapper.sqsj.PreMuImportShuiwuMapper;
import com.industrial.premu.service.IPreMuCompanyTaxService;
import com.industrial.system.api.domain.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class PreMuCompanyTaxServiceImpl implements IPreMuCompanyTaxService {
    @Autowired
    private PreMuCompanyTaxMapper preMuCompanyTaxMapper;

    @Autowired
    private PreMuImportShuiwuMapper preMuImportShuiwuMapper;

    @Autowired
    private PreMuCompanyInfoMapper preMuCompanyInfoMapper;

    /**
     * 导入各部门的记录表
     */
    @Autowired
    private PreMuImportLogMapper preMuImportLogMapper;

    @Value("${file.pre}")
    private String fileDomain;

    /**
     * 查询企业自已填写的税收
     *
     * @param baseId 企业自已填写的税收主键
     * @return 企业自已填写的税收
     */
    @Override
    public PreMuCompanyTax selectPreMuCompanyTaxByBaseId(String baseId)
    {
        return preMuCompanyTaxMapper.selectPreMuCompanyTaxByBaseId(baseId);
    }

    /**
     * 查询企业自已填写的税收列表
     *
     * @param preMuCompanyTax 企业自已填写的税收
     * @return 企业自已填写的税收
     */
    @Override
    public List<PreMuCompanyTax> selectPreMuCompanyTaxList(PreMuCompanyTax preMuCompanyTax)
    {
        return preMuCompanyTaxMapper.selectPreMuCompanyTaxList(preMuCompanyTax);
    }

    /**
     * 新增企业自已填写的税收
     *
     * @param preMuCompanyTax 企业自已填写的税收
     * @return 结果
     */
    @Override
    public int insertPreMuCompanyTax(PreMuCompanyTax preMuCompanyTax)
    {

        PreMuCompanyInfo preMuCompanyInfo = preMuCompanyInfoMapper.selectCompanyInfoUsccAndYear(preMuCompanyTax.getUscc(), preMuCompanyTax.getYears());
        if(preMuCompanyInfo == null){
            throw new RuntimeException(String.format("%s年的企业基本信息中不存在%s",preMuCompanyTax.getYears(),preMuCompanyTax.getCompanyName()));
        }

        int count = preMuCompanyTaxMapper.selectCurrentYearCompanyCount(preMuCompanyTax.getYears(),preMuCompanyTax.getUscc());
        if(count > 0){
            throw new RuntimeException(String.format("当前企业%s已经提交过%s年的税务数据",preMuCompanyTax.getCompanyName(),preMuCompanyTax.getYears()));
        }

        if(preMuCompanyTax.getActualTax() == null || preMuCompanyTax.getActualTax().compareTo(BigDecimal.ZERO) < 1){
            preMuCompanyTax.setActualTax(BigDecimal.ZERO);
        }

        if(preMuCompanyTax.getMainIncome() == null || preMuCompanyTax.getMainIncome().compareTo(BigDecimal.ZERO) < 1){
            preMuCompanyTax.setMainIncome(BigDecimal.ZERO);
        }


        preMuCompanyTax.setBaseId(IdUtil.simpleUUID());
        preMuCompanyTax.setBaseCreateTime(DateUtils.getNowDate());
        preMuCompanyTax.setBaseUpdateTime(DateUtils.getNowDate());
        preMuCompanyTax.setBaseCreateBy(SecurityUtils.getUserId());
        preMuCompanyTax.setBaseUpdateBy(SecurityUtils.getUserId());
        if(StringUtils.isNotBlank(preMuCompanyTax.getFjPath())){
            String s = StrUtil.removePrefix(preMuCompanyTax.getFjPath(), fileDomain);
            preMuCompanyTax.setFjPath("/file" + s);
        }
        return preMuCompanyTaxMapper.insertPreMuCompanyTax(preMuCompanyTax);
    }


    /**
     * 修改企业自已填写的税收
     *
     * @param preMuCompanyTax 企业自已填写的税收
     * @return 结果
     */

    @Override
    public int updatePreMuCompanyTax(PreMuCompanyTax preMuCompanyTax)
    {
        if(StringUtils.isBlank(preMuCompanyTax.getStatus())
                || StringUtils.isBlank(preMuCompanyTax.getBaseId())){
            throw new RuntimeException("没有找到状态或者唯一标识");
        }

        if(preMuCompanyTax.getActualTax() == null || preMuCompanyTax.getActualTax().compareTo(BigDecimal.ZERO) < 1){
            preMuCompanyTax.setActualTax(BigDecimal.ZERO);
        }

        if(preMuCompanyTax.getMainIncome() == null || preMuCompanyTax.getMainIncome().compareTo(BigDecimal.ZERO) < 1){
            preMuCompanyTax.setMainIncome(BigDecimal.ZERO);
        }

        preMuCompanyTax.setBaseUpdateTime(DateUtils.getNowDate());
        preMuCompanyTax.setBaseUpdateBy(SecurityUtils.getUserId());
        if(StringUtils.isNotBlank(preMuCompanyTax.getFjPath())){
            String s = StrUtil.removePrefix(preMuCompanyTax.getFjPath(), fileDomain);
            preMuCompanyTax.setFjPath("/file" + s);
        }
        preMuCompanyTax.setStatus("0");
        preMuCompanyTax.setRejection(null);
        return preMuCompanyTaxMapper.updatePreMuCompanyTax(preMuCompanyTax);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int updateStatus(PreMuCompanyTax preMuCompanyTax) {
        if(StringUtils.equals(preMuCompanyTax.getStatus(),"1")){
            int i = preMuCompanyTaxMapper.updatePreMuCompanyTax(preMuCompanyTax);
            PreMuCompanyTax dbPreMuCompanyInfo = preMuCompanyTaxMapper.selectPreMuCompanyTaxByBaseId(preMuCompanyTax.getBaseId());
            PreMuImportShuiwu preMuImportShuiwu = new PreMuImportShuiwu();
            BeanUtil.copyProperties(dbPreMuCompanyInfo,preMuImportShuiwu);
            preMuImportShuiwu.setYear(dbPreMuCompanyInfo.getYears());
            PreMuImportShuiwu oldDbOPreMuImportShuiwu = preMuImportShuiwuMapper.selectPreMuImportShuiwuInfoByUsccAndYears(preMuImportShuiwu);
            if(oldDbOPreMuImportShuiwu != null && StringUtils.isNotBlank(oldDbOPreMuImportShuiwu.getId())){
                //更新
                preMuImportShuiwu.setId(oldDbOPreMuImportShuiwu.getId());
                preMuImportShuiwu.setDelFlag("0");
                preMuImportShuiwuMapper.updatePreMuImportShuiwu(preMuImportShuiwu);
            }else{
                //新增
                preMuImportShuiwu.setId(IdUtil.simpleUUID());
                preMuImportShuiwu.setDelFlag("0");
                preMuImportShuiwuMapper.insertPreMuImportShuiwu(preMuImportShuiwu);

                //更新税务局导入数据的数量
                //审核通过的接口只能区县调用，这里需要获取当前登陆人的所在的行政区
                SysUser sysUser = SecurityUtils.getLoginUser().getSysUser();
                //省
                String province = sysUser.getProvince();
                //市
                String city = sysUser.getCity();
                //县
                String district = sysUser.getDistrict();

                //查询该企业是规上还是规下
                PreMuCompanyInfo companyInfo = preMuCompanyInfoMapper.selectCompanyInfoUsccAndYear(preMuImportShuiwu.getUscc(),preMuImportShuiwu.getYear());

                String deptCode = "";
                if(companyInfo == null){
                    throw new RuntimeException("该企业没有在企业基本信息中存在");
                }

                if(StringUtils.equals(companyInfo.getCompanyType(),"1")){
                    deptCode = "04";
                }else if(StringUtils.equals(companyInfo.getCompanyType(),"2")){
                    deptCode = "09";
                }else{
                    throw new RuntimeException("没有找到该企业的企业类型");
                }

                PreMuImportLog preMuImportLog = preMuImportLogMapper.selectCurrentDistrictDeptInfo(province, city, district, preMuImportShuiwu.getYear(),deptCode);
                if(preMuImportLog != null){
                    //更新
                    preMuImportLog.setDeptCodeSum(preMuImportLog.getDeptCodeSum() + 1);
                    preMuImportLog.setUpdateDate(DateUtils.getNowDate());
                    preMuImportLog.setUpdateBy(SecurityUtils.getUserId());
                    preMuImportLogMapper.updatePreMuImportLog(preMuImportLog);
                }else{
                    //新增
                    preMuImportLog = new PreMuImportLog();
                    preMuImportLog.setId(IdUtil.simpleUUID());
                    preMuImportLog.setCreateDate(DateUtils.getNowDate());
                    preMuImportLog.setCreateBy(SecurityUtils.getUserId());
                    preMuImportLog.setUpdateDate(DateUtils.getNowDate());
                    preMuImportLog.setUpdateBy(SecurityUtils.getUserId());
                    preMuImportLog.setProvince(province);
                    preMuImportLog.setCity(city);
                    preMuImportLog.setCounty(district);
                    preMuImportLog.setDeptCode(deptCode);
                    preMuImportLog.setDeptCodeSum(1L);
                    preMuImportLog.setDelFlag("0");
                    preMuImportLog.setYear(preMuImportShuiwu.getYear());
                    preMuImportLogMapper.insertPreMuImportLog(preMuImportLog);
                }

            }
            return i;
        }else if(StringUtils.equals(preMuCompanyTax.getStatus(),"2")){
            if(StringUtils.isBlank(preMuCompanyTax.getRejection())){
                throw new RuntimeException("请填写驳回理由");
            }
            return preMuCompanyTaxMapper.updatePreMuCompanyTax(preMuCompanyTax);
        }else{
            throw new RuntimeException("未找到合理的驳回选项");
        }
    }

    /**
     * 批量更新状态
     *
     * @param usccs 社会统一信用代码的数组
     * @param years 年份
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void batchUpdateStatus(List<String> usccs, String years) {
        //查询用户税收表中的数据
        List<PreMuCompanyTax> result = preMuCompanyTaxMapper.selectPreMuCompanyTaxListByUsccsAndYears(usccs,years);
        //查询导入的税务表中的数据
        List<PreMuImportShuiwu> importShuiWuList = preMuImportShuiwuMapper.selectPreMuImportShuiwuInfoByUsccsAndYears(usccs,years);

        List<PreMuImportShuiwu> insertDataList = new ArrayList<>();
        List<PreMuImportShuiwu> updateDataList = new ArrayList<>();

        //查询企业的企业类型
        List<PreMuCompanyInfo> preMuCompanyInfos = preMuCompanyInfoMapper.selectCompanyTypeByUsccArgsAndYears(usccs, years);

        if(preMuCompanyInfos == null || preMuCompanyInfos.isEmpty()){
            throw new RuntimeException("查询企业类型失败");
        }
        //对企业Uscc和企业类型进行映射
        Map<String, String> usccToCompanyTypeMapping = preMuCompanyInfos.stream().collect(Collectors.toMap(k -> k.getUscc(), v -> v.getCompanyType()));

        //表示规上和规下企业有多少条数据
        int gsCount = 0;
        int gxCount = 0;

        if(importShuiWuList != null && !importShuiWuList.isEmpty()){
            Map<String, String> oldDataMap = importShuiWuList.stream().collect(Collectors.toMap(k -> k.getUscc(), v -> v.getId()));
            for(PreMuCompanyTax item : result){
                if(oldDataMap.containsKey(item.getUscc())){
                    //如果存在则更新
                    PreMuImportShuiwu preMuImportShuiwu = new PreMuImportShuiwu();
                    BeanUtil.copyProperties(item,preMuImportShuiwu,"uscc","years");
                    preMuImportShuiwu.setId(oldDataMap.get(item.getUscc()));
                    preMuImportShuiwu.setUpdateDate(DateUtils.getNowDate());
                    preMuImportShuiwu.setUpdateBy(SecurityUtils.getUserId());
                    preMuImportShuiwu.setDelFlag("0");
                    updateDataList.add(preMuImportShuiwu);
                }else{
                    //查询当前企业是规上还是规下
                    String currentCompanyType = usccToCompanyTypeMapping.get(item.getUscc());
                    if(StringUtils.equals(currentCompanyType,"1")){
                        gsCount++;
                    }else if(StringUtils.equals(currentCompanyType,"2")){
                        gxCount++;
                    }else{
                        throw new RuntimeException("非法企业类型");
                    }
                    //不存在则插入
                    PreMuImportShuiwu preMuImportShuiwu = new PreMuImportShuiwu();
                    BeanUtil.copyProperties(item,preMuImportShuiwu);
                    preMuImportShuiwu.setId(IdUtil.simpleUUID());
                    preMuImportShuiwu.setYear(item.getYears());
                    preMuImportShuiwu.setCreateBy(SecurityUtils.getUserId());
                    preMuImportShuiwu.setCreateDate(DateUtils.getNowDate());
                    preMuImportShuiwu.setDelFlag("0");
                    insertDataList.add(preMuImportShuiwu);
                }

                if(updateDataList.size() > 100){
                    preMuImportShuiwuMapper.batchUpdateById(updateDataList);
                    updateDataList.clear();
                    System.gc();
                }

                if(insertDataList.size() > 100){
                    preMuImportShuiwuMapper.batchInsert(insertDataList);
                    insertDataList.clear();
                    System.gc();
                }
            }
            if(!updateDataList.isEmpty()){
                preMuImportShuiwuMapper.batchUpdateById(updateDataList);
                updateDataList.clear();
                System.gc();
            }

            if(!insertDataList.isEmpty()){
                preMuImportShuiwuMapper.batchInsert(insertDataList);
                insertDataList.clear();
                System.gc();
            }
        }else{
            //如果importShuiWuList等于空，批量申核后将所有的数据全部插入
            for(PreMuCompanyTax item : result){

                //查询当前企业是规上还是规下
                String currentCompanyType = usccToCompanyTypeMapping.get(item.getUscc());
                if(StringUtils.equals(currentCompanyType,"1")){
                    gsCount++;
                }else if(StringUtils.equals(currentCompanyType,"2")){
                    gxCount++;
                }else{
                    throw new RuntimeException("未法企业类型");
                }

                //不存在则插入
                PreMuImportShuiwu preMuImportShuiwu = new PreMuImportShuiwu();
                BeanUtil.copyProperties(item,preMuImportShuiwu);
                preMuImportShuiwu.setId(IdUtil.simpleUUID());
                preMuImportShuiwu.setYear(item.getYears());
                preMuImportShuiwu.setCreateBy(SecurityUtils.getUserId());
                preMuImportShuiwu.setCreateDate(DateUtils.getNowDate());
                preMuImportShuiwu.setDelFlag("0");
                insertDataList.add(preMuImportShuiwu);
                if(insertDataList.size() > 100){
                    insertDataList.clear();
                    System.gc();
                }
            }
            if(!insertDataList.isEmpty()){
                preMuImportShuiwuMapper.batchInsert(insertDataList);
                insertDataList.clear();
                System.gc();
            }
        }

        if(result != null && !result.isEmpty()){
            List<PreMuCompanyTax> collect = result.stream().map(k -> {
                PreMuCompanyTax p = new PreMuCompanyTax();
                p.setBaseId(k.getBaseId());
                p.setStatus("1");
                return p;
            }).collect(Collectors.toList());
            if(collect != null && !collect.isEmpty()){
                preMuCompanyTaxMapper.updateBatchPreMuCompanyTax(collect);
            }
        }





        //保存导入记录
        SysUser sysUser = SecurityUtils.getLoginUser().getSysUser();
        //省
        String province = sysUser.getProvince();
        //市
        String city = sysUser.getCity();
        //区
        String district = sysUser.getDistrict();

        //存在规上企业
        if(gsCount > 0){
            PreMuImportLog preMuImportLog = preMuImportLogMapper.selectCurrentDistrictDeptInfo(province, city, district, years, "04");
            if(preMuImportLog != null){
                Long deptCodeSum = preMuImportLog.getDeptCodeSum();
                PreMuImportLog preMuImportLogUpdateParams = new PreMuImportLog();
                preMuImportLogUpdateParams.setDeptCodeSum(deptCodeSum + gsCount);
                preMuImportLogUpdateParams.setId(preMuImportLog.getId());
                preMuImportLogUpdateParams.setUpdateDate(DateUtils.getNowDate());
                preMuImportLogUpdateParams.setUpdateBy(SecurityUtils.getUserId());
                preMuImportLogMapper.updatePreMuImportLog(preMuImportLogUpdateParams);
            }else{
                PreMuImportLog preMuImportLogInsertParams = new PreMuImportLog();
                preMuImportLogInsertParams.setDeptCodeSum(Long.valueOf(gsCount));
                preMuImportLogInsertParams.setId(IdUtil.simpleUUID());
                preMuImportLogInsertParams.setUpdateDate(DateUtils.getNowDate());
                preMuImportLogInsertParams.setUpdateBy(SecurityUtils.getUserId());
                preMuImportLogInsertParams.setCreateDate(DateUtils.getNowDate());
                preMuImportLogInsertParams.setCreateBy(SecurityUtils.getUserId());
                preMuImportLogInsertParams.setDeptCode("04");
                preMuImportLogInsertParams.setYear(years);
                preMuImportLogInsertParams.setDelFlag("0");
                preMuImportLogInsertParams.setProvince(province);
                preMuImportLogInsertParams.setCity(city);
                preMuImportLogInsertParams.setCounty(district);
                preMuImportLogMapper.insertPreMuImportLog(preMuImportLogInsertParams);
            }
        }


        //存在规下企业
        if(gxCount > 0){
            PreMuImportLog preMuImportLog = preMuImportLogMapper.selectCurrentDistrictDeptInfo(province, city, district, years, "09");
            if(preMuImportLog != null){
                Long deptCodeSum = preMuImportLog.getDeptCodeSum();
                PreMuImportLog preMuImportLogUpdateParams = new PreMuImportLog();
                preMuImportLogUpdateParams.setDeptCodeSum(deptCodeSum + gxCount);
                preMuImportLogUpdateParams.setId(preMuImportLog.getId());
                preMuImportLogUpdateParams.setUpdateDate(DateUtils.getNowDate());
                preMuImportLogUpdateParams.setUpdateBy(SecurityUtils.getUserId());
                preMuImportLogMapper.updatePreMuImportLog(preMuImportLogUpdateParams);
            }else{
                PreMuImportLog preMuImportLogInsertParams = new PreMuImportLog();
                preMuImportLogInsertParams.setDeptCodeSum(Long.valueOf(gxCount));
                preMuImportLogInsertParams.setId(IdUtil.simpleUUID());
                preMuImportLogInsertParams.setUpdateDate(DateUtils.getNowDate());
                preMuImportLogInsertParams.setUpdateBy(SecurityUtils.getUserId());
                preMuImportLogInsertParams.setCreateDate(DateUtils.getNowDate());
                preMuImportLogInsertParams.setCreateBy(SecurityUtils.getUserId());
                preMuImportLogInsertParams.setDeptCode("09");
                preMuImportLogInsertParams.setYear(years);
                preMuImportLogInsertParams.setDelFlag("0");
                preMuImportLogInsertParams.setProvince(province);
                preMuImportLogInsertParams.setCity(city);
                preMuImportLogInsertParams.setCounty(district);
                preMuImportLogMapper.insertPreMuImportLog(preMuImportLogInsertParams);
            }
        }
    }

    /**
     * 批量删除企业自已填写的税收
     *
     * @param baseIds 需要删除的企业自已填写的税收主键
     * @return 结果
     */
    @Override
    public int deletePreMuCompanyTaxByBaseIds(String[] baseIds)
    {
        return preMuCompanyTaxMapper.deletePreMuCompanyTaxByBaseIds(baseIds);
    }

    /**
     * 删除企业自已填写的税收信息
     *
     * @param baseId 企业自已填写的税收主键
     * @return 结果
     */
    @Override
    public int deletePreMuCompanyTaxByBaseId(String baseId)
    {
        return preMuCompanyTaxMapper.deletePreMuCompanyTaxByBaseId(baseId);
    }

    @Override
    public PreMuCompanyTax getCompanyInfoByCompanyId() {
        String uscc = SecurityUtils.getUsername();
        LocalDate localDate = LocalDate.now();
        PreMuCompanyTax preMuCompanyTax = preMuCompanyTaxMapper.getCompanyInfoByCompanyId(uscc, String.valueOf(localDate.getYear() - 1));
        if(preMuCompanyTax != null && StringUtils.isNotBlank(preMuCompanyTax.getFjPath())){
            String name = FileNameUtil.getName(preMuCompanyTax.getFjPath());
            preMuCompanyTax.setFjName(name);
        }

        if(preMuCompanyTax == null){
            preMuCompanyTax = new PreMuCompanyTax();
        }
        return preMuCompanyTax;
    }

}
